#ifndef _MAE378_UTILITY_H_
#define _MAE378_UTILITY_H_ 1

#include "mae378_defines.h"


/**
 * Pauses for the specified number of ms, which can be bigger than 10.
 */
void delay(uint16_t ms)
{
	while(ms > 16)
	{
		_delay_ms(16);
		ms -= 16;
	}
	_delay_ms(ms);
}


void setPort(uint8_t *port, uint8_t val)
{
	*port = val;
}


uint8_t* getPort(PortPin_t p)
{
	uint8_t portNumber = (p & 0b00011000) >> 3;
	switch(portNumber)
	{
		case 0:
			return &PORTA;
		case 1:
			return &PORTB;
		case 2:
			return &PORTC;
		case 3:
			return &PORTD;
	}
	return NULL;
}

uint8_t* getPinArray(PortPin_t p)
{
	uint8_t portNumber = (p & 0b00011000) >> 3;
	switch(portNumber)
	{
		case 0:
			return &PINA;
		case 1:
			return &PINB;
		case 2:
			return &PINC;
		case 3:
			return &PIND;
	}
	return NULL;
}

uint8_t getPinMask(PortPin_t p)
{
	return 1 << (p & 0b00000111);
}


uint8_t getOutputPin(PortPin_t p)
{
	uint8_t *port, pin;

	port = getPort(p);
	pin = getPinMask(p);

	return (*port & pin) ? ON : OFF;
}


uint8_t getInputPin(PortPin_t p)
{
	uint8_t *port, pin;

	port = getPinArray(p);
	pin = getPinMask(p);

	return (*port & pin) ? ON : OFF;
}

void setPin(PortPin_t p)
{
	uint8_t *port, pin;

	port = getPort(p);
	pin = getPinMask(p);

	*port |= pin;
}

void clearPin(PortPin_t p)
{
	uint8_t *port, pin;

	port = getPort(p);
	pin = getPinMask(p);

	*port &= (pin ^ 0b11111111);
}


#endif	// _MAE378_UTILITY_H_
